### Project 7 Ultrasonic Sensor **1.Description** ![](media/wps1-1766471052484-1.jpg) The ultrasonic sensor uses sonar to determine distance to an object like bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package. It comes complete with an ultrasonic transmitter and a receiver module. The ultrasonic sensor is being used in a wide range of electronic projects for creating obstacle detection and distance measuring application as well as various other applications. In this project, we will work to show simple ways for distance with pico and the ultrasonic sensor, and learn how to use the sensor in arduino IDE. **2.Parameters and Principle** - Working voltage:+5V DC - Quiescent current: <2mA - Working current: 15mA - Sensing angle: <15° - Distance range: 2cm – 400 cm - Precision: 0.3 cm - Measuring angle: 30 degree - Input trigger pulse: 10us Principle: The ultrasonic transmitter emits ultrasonic waves in a certain direction, and the counter starts timing at the same time of the launch. The ultrasonic wave spreads in the air and is immediately reflected back when encountering obstacles on the way. When it stops timing immediately, the ultrasonic wave is also a sound wave whose speed V is related to temperature. Generally, the transmission speed of the wave in the air is 340m/s. According to the time t recorded by the timer, the distance s from the launching point to the obstacle surface can be calculated, that is, S =340t/2: (1) Pull down TRIG then trigger high level signals with least 10us; (2) After triggering, the module will automatically send eight 40KHz ultrasonic pulses and detect whether there is a signal return; (3) If there is a signal return, ECHO outputs a high level, the high level read by the microcontroller time duration is the time of the ultrasonic wave from transmitting to returning. **3.Test Code** ``` from machine import Pin,I2C import mecanumCar_v2 import time i2c = I2C(0, sda = Pin(20), scl = Pin(21), freq = 400000) mecanumCar = mecanumCar_v2.Driver(i2c) while True: distance = mecanumCar.get_distance() print("distance is : {} cm".format(distance)) time.sleep_ms(100) ``` 4.Test Result After powering on, click ![img](media/wps1-1766564679774-1.jpg) to run test code, then we can see the distance measured by the ultrasonic module in Shell, and move the car to see that the distance is also changing, as shown below: ![](media/wps2-1766564687361-3.jpg) **5.Code Explanation** | mecanumCar.get_distance() | Trig is connected to GPIO3,Echo is connected to GPIO4 | | --------------------------------------------- | ------------------------------------------------------------ | | print("distance is : {} cm".format(distance)) | The string format is printed, and the measured distance is displayed in {} | | time.sleep_ms(100) | Delay in 100ms |